package com.naihe.anderson.sms.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.naihe.anderson.sms.R;
import com.naihe.anderson.sms.adapter.RecordInfoAdapter;
import com.naihe.anderson.sms.application.NhSmsApp;
import com.naihe.anderson.sms.constants.NhSmsConstants;
import com.naihe.anderson.sms.entity.RecordMoney;
import com.naihe.anderson.sms.listener.OnRecordListener;
import com.naihe.anderson.sms.manager.RecordMoneyMgr;
import com.naihe.anderson.sms.widgets.LongClickDialog;
import com.naihe.anderson.sms.widgets.RoundedRectListView;
import com.naihe.anderson.sms.widgets.calendar.CalendarActivity;

public class RecordMainActivity extends Activity implements OnClickListener,OnItemClickListener, OnItemLongClickListener, OnRecordListener{
	
	Button change_btn;
	Button back_btn;
	
	LinearLayout search_calendar_layout;
	TextView calendar_time;
	
	NhSmsApp nhSmsApp;
	RecordMoneyMgr moneyMgr;
	
	ListView record_info_list;
	RecordInfoAdapter infoAdapter;
	List<RecordMoney> recordMoneys = new ArrayList<RecordMoney>();
	
	public static final int REQUEST_SEARCH_CALENDAR = 112233;
	
	public static final int MSG_WHAT_DATECHANGE_ACTIVITY = 0;
	public static final int MSG_WHAT_DO_DATE = 1;
	public static final int MSG_WHAT_SEARCH_TIME = 2;
	public static final int MSG_WHAT_SEARCH_DATA = 3;
	Handler mHandler = new Handler(){

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_WHAT_DATECHANGE_ACTIVITY:
				recordMoneys.clear();
				recordMoneys.addAll(moneyMgr.getRecordMoneyList());
				infoAdapter.notifyDataSetChanged();
				break;
			case MSG_WHAT_DO_DATE:
				recordMoneys.addAll(moneyMgr.getRecordMoneyList());
				infoAdapter.notifyDataSetChanged();
				break;
			case MSG_WHAT_SEARCH_TIME:
				Bundle bundle = msg.getData();
				String searchTime = bundle.getString("searchTime");
				calendar_time.setText(searchTime);
				
				long beginTime = bundle.getLong("beginTime");
				long endTime = bundle.getLong("endTime");
				Message message = new Message();
				message.what = MSG_WHAT_SEARCH_DATA;
				moneyMgr.searchRecordMoney(beginTime, endTime, mHandler, message);
				break;
			case MSG_WHAT_SEARCH_DATA:
				recordMoneys.clear();
				recordMoneys.addAll((ArrayList<RecordMoney>) msg.obj);
				infoAdapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		}
	};
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.record_main_layout);
        nhSmsApp = (NhSmsApp) getApplication();
        nhSmsApp.setActivity(this);
        moneyMgr = nhSmsApp.getRecordMoneyMgr();
        
        moneyMgr.setOnRecordListener(this);
        initView();
        
        if(mHandler != null)
        	mHandler.sendEmptyMessageDelayed(MSG_WHAT_DO_DATE, 100);
    }
	
	public void initView(){
		search_calendar_layout = (LinearLayout) findViewById(R.id.search_calendar_layout);
		search_calendar_layout.setOnClickListener(this);
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("(yyyy年MM月)");
		calendar_time = (TextView) findViewById(R.id.calendar_time);
		calendar_time.setText(dateFormat.format(new Date()));
		
		change_btn = (Button) findViewById(R.id.change_btn);
		change_btn.setOnClickListener(this);

		back_btn = (Button) findViewById(R.id.back_btn);
		back_btn.setOnClickListener(this);
		
		record_info_list = (ListView) findViewById(R.id.record_info_list);
		infoAdapter = new RecordInfoAdapter(RecordMainActivity.this, recordMoneys);
		record_info_list.setAdapter(infoAdapter);
		record_info_list.setOnItemLongClickListener(this);
	}

	PopupWindow mPopupWindow = null;
	private void initPopupWindows(){
		String[] muenString = new String[]{getResources().getString(R.string.money_001),getResources().getString(R.string.money_002)};
		LayoutInflater mLayoutInflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);  
        View popunwindwow = mLayoutInflater.inflate( R.layout.menu_popup, null);
        RoundedRectListView menuListView = (RoundedRectListView) popunwindwow.findViewById(R.id.menuListView);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(RecordMainActivity.this, R.layout.simple_list_item, muenString);
        menuListView.setAdapter(adapter);
        menuListView.setOnItemClickListener(this);
        
        mPopupWindow = new PopupWindow(popunwindwow, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); 
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());//点击窗口外消失  
        mPopupWindow.setOutsideTouchable(true);  
        mPopupWindow.setFocusable(true);
	}
	
	private void toFinishAvtivity(){
		infoAdapter.clear();
		nhSmsApp.setActivity(null);
		moneyMgr.setOnRecordListener(null);
		RecordMainActivity.this.finish();
		System.gc();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(data == null || data.getExtras() == null)
			return;
		if (requestCode == REQUEST_SEARCH_CALENDAR && resultCode == RESULT_OK) {
			long beginTime = 0;
			long endTime = 0;
			int type = data.getIntExtra("type", 0);
			int year = 0;
			int month = 0;
			int day = 1;
			
			String searchTime = "";
			
			year = Integer.parseInt(data.getStringExtra("year")) - 1900;
			month = Integer.parseInt(data.getStringExtra("month")) - 1;
			if(type == 1){//日查询
				day = Integer.parseInt(data.getStringExtra("day"));
				Date beginDate = new Date(year, month, day);
				Date endDate = new Date(year, month, day+1);
				SimpleDateFormat dateFormat = new SimpleDateFormat("(yyyy年MM月dd日)");
				searchTime = dateFormat.format(beginDate);
				beginTime = beginDate.getTime();
				endTime = endDate.getTime();
			} else {
				Date beginDate = new Date(year, month, day);
				Date endDate = new Date(year, month + 1, day);
				SimpleDateFormat dateFormat = new SimpleDateFormat("(yyyy年MM月)");
				searchTime = dateFormat.format(beginDate);
				beginTime = beginDate.getTime();
				endTime = endDate.getTime();
			}
			
			Message message = new Message();
			message.what = MSG_WHAT_SEARCH_TIME;
			Bundle bundle = new Bundle();
			bundle.putLong("beginTime", beginTime);
			bundle.putLong("endTime", endTime);
			bundle.putString("searchTime", searchTime);
			message.setData(bundle);
			mHandler.sendMessage(message);
		}
	}
	
	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.back_btn){
			toFinishAvtivity();
		} else if(v.getId() == R.id.change_btn){
			if(mPopupWindow == null)
				initPopupWindows();
			mPopupWindow.update();
			mPopupWindow.showAsDropDown(v);
		} else if(v.getId() == R.id.search_calendar_layout){
			Intent intent = new Intent(RecordMainActivity.this, CalendarActivity.class);
			RecordMainActivity.this.startActivityForResult(intent, REQUEST_SEARCH_CALENDAR);
		}
	}

	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 截获按键事件
        if(KeyEvent.KEYCODE_BACK == keyCode){
        	toFinishAvtivity();
        	return true;
		}

        return super.onKeyDown(keyCode, event);
    }

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		@SuppressWarnings("unchecked")
		String opter = ((ArrayAdapter<String>)parent.getAdapter()).getItem(position);
		if(opter.equals(getResources().getString(R.string.money_001))){
			Intent intent = new Intent(RecordMainActivity.this, NewExpenditureActivity.class);  
            startActivity(intent);
		} else if(opter.equals(getResources().getString(R.string.money_002))){
			Intent intent = new Intent(RecordMainActivity.this, NewIncomeActivity.class);  
            startActivity(intent);
		}
		mPopupWindow.dismiss();
	}

	@Override
	public void onDataChanged() {
		mHandler.sendEmptyMessage(MSG_WHAT_DATECHANGE_ACTIVITY);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		final RecordMoney recordMoney = infoAdapter.getItem(position);
		if(recordMoney == null) return false;
		
		List<String> opterList = new ArrayList<String>();
		opterList.add("删除");
		opterList.add("转便签");
		if(!TextUtils.isEmpty(recordMoney.projectPic)){
			opterList.add("去除图片");
		}
		if(!TextUtils.isEmpty(recordMoney.loation)){
			opterList.add("去除位置");
		}
		
		String[] links = opterList.toArray(new String[opterList.size()]);
		new LongClickDialog(RecordMainActivity.this, links, getResources().getString(R.string.operation), new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(((ArrayAdapter<String>)parent.getAdapter()).getItem(position).equals("删除")){
					moneyMgr.deltetRecordMoney(recordMoney);
				} else if(((ArrayAdapter<String>)parent.getAdapter()).getItem(position).equals("转便签")){
					moneyMgr.moneyToNote(recordMoney);
				} else if(((ArrayAdapter<String>)parent.getAdapter()).getItem(position).equals("去除图片")){
					moneyMgr.removePic(recordMoney, NhSmsConstants.MONRY_PREFIX);
				} else if(((ArrayAdapter<String>)parent.getAdapter()).getItem(position).equals("去除位置")){
					moneyMgr.removePic(recordMoney, NhSmsConstants.MONRY_MAP_PREFIX);
				}
			}
		}).show();
		return false;
	}

}
